package com.dayang.framework.biz.limiter.config;

import com.dayang.framework.biz.limiter.aspect.RateLimiterAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

/**
 * @author: dayang
 * @since: 2024/6/13
 * @description:
 */
@Configuration
public class RateLimiterAutoConfiguration {

    @Bean
    public RateLimiterAspect limiterAspect(RedisTemplate<String,Object> redisTemplate){
        return new RateLimiterAspect(redisTemplate,limitScript());
    }

    @Bean
    public DefaultRedisScript<Long> limitScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        // 加载lua脚本
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/limiter.lua")));
        // 返回之类型为Long
        redisScript.setResultType(Long.class);
        return redisScript;
    }
}
